package com.lepu.app.fun.tool.cjsj;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.AppEnterTongJi;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.eyzhs.app.R;
import com.lepu.app.fun.mother_circle.MotherTopicActivity;
import com.lepu.app.fun.tool.cjsj.adapter.ToolChanJianAdapter;
import com.lepu.app.fun.tool.cjsj.bean.BeanToolChanJian;
import com.lepu.app.fun.tool.ymsjb.remind.Alarm;
import com.lepu.app.fun.tool.ymsjb.remind.AlarmTipsManager;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class ChanJianActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, Observer, AsyncRequest, OnRefreshListener, OnLoadListener{
	
	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;

	private int mCurrentPage = 1;
	
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	public ListView mListView;
	public ToolChanJianAdapter mAdapter;
	public ArrayList<BeanToolChanJian> mArrayList;
	public ArrayList<LinearLayout> mViewList;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tool_chanjian_activity);

		UtilityBase.setStatusBarRes(this, R.color.color_bmi, true);
		init();
	}

	@Override
	public void onResume() {
		super.onResume();
		
	}
	
	@Override
	public void onDestroy() {
		ObserverManager.getInstance().removeObserver(ObserverConst.NOTIFY_CHANJIAN_CHANGE);
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	
	/**
	 * 初始化方法
	 */
	@SuppressLint("InflateParams")
	@SuppressWarnings("deprecation")
	private void init() {
		ObserverManager.getInstance().addObserver(ObserverConst.NOTIFY_CHANJIAN_CHANGE, this);
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("产检时间表");
		topbar.setTopbarBackground(R.color.color_bmi);
		topbar.setonTopbarNewLeftLayoutListener(this);

		mListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);
		
		
		mViewList = new ArrayList<LinearLayout>();
		
		View view = LayoutInflater.from(this).inflate(R.layout.chanjian_head_view, null);
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView1)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView2)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView3)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView4)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView5)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView6)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView7)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView8)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView9)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView10)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView11)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView12)));
		mViewList.add((LinearLayout)(view.findViewById(R.id.topView13)));
		
		for(int i=0; i<mViewList.size(); i++){
			final int index = i;
			mViewList.get(i).setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					 Intent intent = new Intent(ChanJianActivity.this, AppBroswerActivity.class);
					 String url = "http://dl.eyzhs.com/static/check/check"+(index+1)+".html";
					 intent.putExtra("url", url);
                     intent.putExtra("need_share", false);
                     intent.putExtra("title", "");
                     intent.putExtra("cover", "");
					intent.putExtra("top_color_id",R.color.color_bmi);
                     startActivity(intent,true);
				}
			});
		}
		
		
        TextView addText = (TextView) view.findViewById(R.id.addText);
        addText.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				AppEnterTongJi.clickEvent(81, "");
				startActivity(new Intent(ChanJianActivity.this, ChanJianAddActivity.class),true);
			}
		});
        
        
        mArrayList = new ArrayList<BeanToolChanJian>(); 
        mAdapter = new ToolChanJianAdapter(this, mArrayList);
        
        mListView.addHeaderView(view);
		mListView.setAdapter(mAdapter);
		
		request(false);
	}

	
	//请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		String url =  Setting.getDataChanjianUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true,false,true);
	}
	

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				ArrayList<BeanToolChanJian> dataList = (ArrayList<BeanToolChanJian>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					mArrayList.clear();
					mArrayList.addAll(dataList);
					mAdapter.notifyDataSetChanged();
				} else {
					mArrayList.clear();
					mAdapter.notifyDataSetChanged();
					UIHelper.showToast(MotherTopicActivity.getInstance(), R.string.no_data);
				}

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				if (mArrayList != null && mArrayList.size() > 0) {
					if (mArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:
				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<BeanToolChanJian> dataMoreList = (ArrayList<BeanToolChanJian>) msg.obj;
				
				if (dataMoreList != null && dataMoreList.size() > 0) {
					
				    mAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(MotherTopicActivity.getInstance(), R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;

			default:
				break;
			}
		};
	};
	
	public void setRemind(ArrayList<BeanToolChanJian> beanList){
		for(int i=0; i<beanList.size(); i++){
			BeanToolChanJian bean = beanList.get(i);
			if(bean.remindIs == 1){
				long alarmTime = DateUtil.getLongTimeAll(bean.date +" "+bean.remindTime);
				if(bean.remindIndex == 0){  //当天
					
				}else if(bean.remindIndex == 1){  //前一天
					alarmTime = alarmTime - DateUtil.DAY_MILLIS;
				}else if(bean.remindIndex == 2){  //前三天
					alarmTime = alarmTime - (DateUtil.DAY_MILLIS * 3);
				}
				
				String timeStr = String.valueOf(alarmTime);
			    int alarmId = Integer.valueOf(timeStr.substring(timeStr.length() - 8, timeStr.length()));
			    
			    //如果闹钟不存在就设置
			    if(!AlarmTipsManager.checkExist(LoginUtil.getUserId(), alarmId)){
			    	//设置闹钟
					Alarm alarm = new Alarm();
					alarm.uid = LoginUtil.getUserId();
					alarm.alarmTime = alarmTime;
					alarm.showTime = bean.remindTime;
					alarm.setTime = alarmTime;
					alarm.note = "您的产检时间临近了，记得按时前往医院检查哦";
					Alarm.setRemind(alarm, MyApplication.alarmManager, ChanJianActivity.this);
			    }
			    
			    //删除提醒
//            	Alarm.closeRemind(MyApplication.alarmManager, this, alarmId);
//              AlarmTipsManager.deleteItem(alarmId); 
			}
		}
	}
	
	@Override
	public void notify(String arg0, Object arg1, Object arg2) {
		request(false);
	}

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			ArrayList<BeanToolChanJian> dataArraylist = BeanToolChanJian.parseJsonData((String) data);
			
			if (dataArraylist != null && dataArraylist.size() > 0) {
				setRemind(dataArraylist);
			}
		
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			ArrayList<BeanToolChanJian> dataMoreArraylist = BeanToolChanJian.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				mArrayList.addAll(dataMoreArraylist);
				setRemind(dataMoreArraylist);
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} 
	}
	
}
